﻿using B.S.ProductionProject.Domain;
using B.S.ProductionProject.ErrorCode;
using B.S.ProductionProject.Write.WebAPI.Applications.Commands.ProductionPlanningCommand;
using MediatR;
using SqlSugar;

namespace B.S.ProductionProject.Write.WebAPI.Applications.CommandHandlers.ProductionPlanningCommandHandler
{
    public class DelProductionPlanningCommandHandler : IRequestHandler<DelProductionPlanningCommand, APIResult<object>>
    {
        private readonly ISqlSugarClient db;

        public DelProductionPlanningCommandHandler(ISqlSugarClient db)
        {
            this.db = db;
        }

        public async Task<APIResult<object>> Handle(DelProductionPlanningCommand request, CancellationToken cancellationToken)
        {
            APIResult<object> result = new APIResult<object>();
            result.code = APIResultCode.success;
            result.msg = "删除成功";
            var ids = request.ProductionPlanningIds.Split(',').Select(int.Parse).ToList();

            // 一次性查询所有要删除的计划记录
            var itemsToDelete = await db.Queryable<ProductionPlanning>().Where(p => ids.Contains(p.ProductionPlanningId)).ToListAsync();

            foreach (var item in itemsToDelete)
            {
                item.isDelete = true;
                await db.Updateable(item).ExecuteCommandAsync();
            }

            // 一次性查询所有要删除的计划明细记录
            var iToDelete = await db.Queryable<ProductionScheduleDetail>().Where(p => ids.Contains(p.ProductionPlanningId)).ToListAsync();

            foreach (var item in iToDelete)
            {
                item.isDelete = true;
                await db.Updateable(item).ExecuteCommandAsync();
            }

            return result;
        }
    }
}
